<?php
class School extends MY_Controller {
	
	// array with vars to be used in the layout
	private $data_layout;
	
	// Array with user data
	private $UserData;
	
	// array with pair 'link'=>'name to display' menu entries
	private $menuItems;
	
	// var with the final menu
	private $menu;
	
	/**
	 * array with the name of all content views used in this controler
	 */
	var $views = array(
		'schoolBodyMain'			=>'school/content/schoolBodyMain',
		'schoolBodyOffers'			=>'school/content/schoolBodyOffers',
		'schoolBodyExtras'			=>'school/content/schoolBodyExtras',
		'schoolBodySchedules'		=>'school/content/schoolBodySchedules',
		'schoolBodyReservations'	=>'school/content/schoolBodyReservations',
	);
	
	/**
	 * Constructor ... here is checked if the user is logged in
	 */
	function School() {
		parent::__construct();
		
		// check if a School user is logged in ...
		if ($this->ion_auth->is_group("school")) {
			
			$this->load->helpers(array('html'));
			
			$this->load->library(array('carabiner','template','fuelmenu','ion_auth','mylibrary','json'));
			
			$this->load->model('School_model');
			
			$this->lang->load('school');
			
			$this->carabiner->css('reset.css');
			$this->carabiner->css('school.css');
			$this->carabiner->css('school/grid.css');
			$this->carabiner->css('school/theme-blue.css');
			
			$this->_createMenuNav();
			
			$this->_configTemplate();	
			
			$this->_setData();
		}
		else {		// not a school user? redirect ...
			redirect('Login/index');
		}
	}
	
	
	/**
	 * Config the template library
	 */
	private function _configTemplate() {
		$this->template->title('Radical Booking - School');
		$this->template->enable_parser(false);
		$this->template->set_layout('schoolLayout');
	}
	
	
	/**
	 * set global var's to be forward to all views
	 */
	private function _setData() {
		$school = $this->School_model->getUserInfo($this->ion_auth->get_user()->id);
		$this->template->set('school',$school);
		$this->template->set('ajaxUrl',$this->config->item('school_ajaxUrl'));
	}
	
	/**
	 * Create the Navigation Menu 
	 */
	private function _createMenuNav() {
			
		// create the entries
		$this->menuItems =
		array (
				'School/index'			=>	$this->lang->line('school.menu.main'),
				'School/offers'			=>	$this->lang->line('school.menu.lnk1'),
				'School/extras'			=>	'extras',
				'School/schedules'		=>	$this->lang->line('school.menu.lnk2'),
				'School/reservations'	=>	$this->lang->line('school.menu.lnk3'),
		);
	}
	
	
	/**
	 * function to get the menu to be drawn
	 */
	private function _getMenu() {
		
		// set this link with class="actual"
		$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading');
		
		$param = array(
			'active_class'			=>'actual',
			'use_titles'			=>false,
			'container_tag_id'		=>'nav',
		);
		$this->fuelmenu->initialize($param);
		
		return $this->fuelmenu->render($this->menuItems,$active,NULL,'basic');
	}
	
	
	
	
	
	private function _getMenus() {
		
		$menus = array();
		
		// render the mainMenu
		$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading'); // set the current link as active
		$menus['main'] = $this->fuelmenu->render($this->menuItems,$active,NULL,'basic');
		
		// render the footerMenu
		$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading'); // set the current link as active
		$menus['footer'] = $this->fuelmenu->render($this->menuItems,$active,NULL,'delimited');
		
		// render the loginMenu
		if ($this->ion_auth->logged_in()) {
			$menus['login'] = $this->fuelmenu->render(array('Login/index'=>$this->ion_auth->get_user()->email),null,null,'basic');
		}
		else {
			$menus['login'] = $this->fuelmenu->render(array('Login/index'=>'login'),null,null,'basic');
		}
		
		// render the languageMenu
		$language = array (
			$this->lang->switch_uri('en')=>'en',
			$this->lang->switch_uri('pt')=>'pt',
		);
		$menus['language'] = $this->fuelmenu->render($language,null,null,'basic');
		
		return $menus;
	}
	
	
	private function _setLibraries($libs) {
		
	}
	
	
	
	
	
	
	/**
	 * Main entry point
	 */
	public function index() {
		
		// get layout info to be passed to the view
		$data = $this->School_model->getLayoutInfo();
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		$this->template->set('groupLibraries',array());
		
		$this->template->set('menu',$this->_getMenu());
		
		$this->template->build($this->views['schoolBodyMain']);
	}
	
	/**
	 * Show, edit and create OFFERS
	 */
	public function offers() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','jtable_1.5.1','validationEngine'));
		else 
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','jtable_1.5.1','validationEngine'));
		
		// local assets
		$this->carabiner->js('offers.js');
		
		// render the menu
		$this->template->set('menu',$this->_getMenu());
		
		// load view
		$this->template->build($this->views['schoolBodyOffers']);
	}
	
	
	public function extras() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','jtable_1.5.1','validationEngine'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','jtable_1.5.1','validationEngine'));
		
		// local assets
		$this->carabiner->js('school/extras.js');
		
		// render the menu
		$this->template->set('menu',$this->_getMenu());
		
		// load view
		$this->template->build($this->views['schoolBodyExtras']);
	}
	
	/**
	 * SCHEDULES
	 */
	public function schedules() {
		
		// get layout info to be passed to the view
		$data = $this->School_model->getLayoutInfo();
		
		// choose group libraries to be loaded in the view
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','fullcalendar'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','fullcalendar',));
		
		// load local assets
		$this->carabiner->js('schedules.js');
		
		// render the menu
		$this->template->set('menu',$this->_getMenu());
		
		// load view
		$this->template->build($this->views['schoolBodySchedules']);
	}
	
	/**
	 * RESERVATIONS
	 */
	public function reservations() {
		
		// witch libraries we need in this view? only those will be loaded in the head view file
		if ($this->remoteResources)
			$this->template->set('groupLibraries',array('jquery','jqueryui','datatables'));
		else
			$this->template->set('groupLibraries',array('jquery_local','jqueryui_local','datatables_local'));
		
		// render the menu
		//$active = $this->uri->rsegment(1).$this->uri->slash_rsegment(2,'leading');
		//$data['menu'] = $this->fuelmenu->render($this->menuItems,$active,NULL,'basic');
		$this->template->set('menu',$this->_getMenu());
		
		// load view
		//$this->load->view('School/school_link3',$data);
		$this->template->build($this->views['schoolBodyReservations']);
	}
	
	
	
	
	
	
	/**
	* Logout the School user from the system
	*/
	public function logout() {
		$this->ion_auth->logout();
		redirect('Main/index');
	}
	
	
	
	
	
	
	
	
	
	
	/**
	* Create an offer with the data passed in POST
	*/
	public function createOfferAction() {
	
		// check if all POST fields are ok ... implement this later
	
		// create offer and print the newly created offer in json format
		if (isset($_POST['name']))
			echo $this->School_model->addOffer($_POST);
		else {
			show_404('',false);
		}
	
		//$tmp_Ok = ' { "Result":"OK", "Records":[] } ';
	}
	
	
	
	/**
	 * Send an json object to the jtable with all
	 * offers from the current logged in school user
	 */
	public function readOfferAction() {
		$offers = $this->School_model->getOffer(array('datatype'=>'jtable'));
		//$this->firephp->log($offers);
		echo $offers;
		
		$tmp = '
			{
				"Result":"OK",
				"Records":
				[
					{
						"id":"5",
						"users_id":"7",
						"name":"primeiro",
						"price":"85.00",
						"numberOfClasses":"5",
						"level":"beginner",
						"minPart":"2",
						"maxPart":"8",
						"active":"1",
						"remainingClasses":"5",
						"part":"0",
						"description":"desc 1",
						"tmp":2
					},
					{
						"id":"6",
						"users_id":"7",
						"name":"segundo",
						"price":"25.00",
						"numberOfClasses":"1",
						"level":"beginner",
						"minPart":"2",
						"maxPart":"6",
						"active":"1",
						"remainingClasses":"0",
						"part":"0",
						"description":"Desc ... 2",
						"tmp":3
					}
			],
			"TotalRecordCount":6}';
		//echo $tmp;
		//$tmp_ok = ' { "Result":"OK", "Records":[] }'; //echo $tmp_ok; 
	}

		
	/**
	 * update offer
	 */
	public function updateOfferAction() {
		
		// check if all POST fields are ok ... implement later
		
		// if all fields are ok ... update offer
		if (isset($_POST['id'])) {
			
			// workarround ... jtable dont send active value when its set to 0 ...
			if (!isset($_POST['active'])) { 
				$_POST['active'] = 0;
			}
			//$this->firephp->log($_POST);
			$this->School_model->updateOffer($_POST);
			echo '{"Result":"OK"}'; 
		}
		else {
			echo '{ "Result":"ERROR", "Message":"Error trying to update offer" }';
		}
	}
	
	/**
	 * Delete the offer with id = $_POST['id'] 
	 * A json object with an "ok" or "error" status is printed
	 */
	public function deleteOfferAction() {
		
		// check if 'id' is a valid number ... implement later
		
		if (isset($_POST['id'])) {
			$this->School_model->deleteOffer($_POST['id']);
			echo '{"Result":"OK"}';
		}
		else {
			echo '{ "Result":"ERROR", "Message":"Error trying to delete user" }';
		}
	}
	
	
	
	
	
	public function createExtraAction()	{
		
		$errorMsg = '{ "Result":"ERROR", "Message":"Error while trying to create the extra" }';
		
		//$emptyResult = '{ "Result":"OK", "Records":[]}'; 
		
		// check if post has all fields ok
		
		$result = $this->School_model->createExtra($_POST);
		
		if ($result) {
			echo $result;	
		}
		else {
			echo $errorMsg;
		}
	}
	
	public function readExtraAction() {
		
		$offerId = $this->input->get('offerId');
		
		$noRecords = '{"Result":"OK", "Records":[]}';
		
		if ($offerId == null)
			$records = $this->School_model->readExtra(); 
		else 
			$records = $this->School_model->readExtra(null,$offerId); 
		
		if ($records)
			echo $records;
		else 
			echo $noRecords;
	}	
	
	
	
	public function updateExtraAction() {
		
		// msg to inform
		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{ "Result":"ERROR", "Message":"Error while trying to update the extra" }';
		
		// workarround ... jtable dont send active value when its set to 0 ...
		if (!isset($_POST['active'])) { 
			$_POST['active'] = 0;
		}
		
		if (!isset($_POST['included_in_offer']))
			$_POST['included_in_offer'] = 0;
		
		// update data
		$res = $this->School_model->updateExtra($_POST);
		
		if ($res)
			echo $okMsg;
		else
			echo $errorMsg;
	}
	
	
	public function deleteExtraAction() {
		
		// msg
		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{ "Result":"ERROR", "Message":"Error trying to delete the extra" }';
		
		// validate fields
		
		$res = $this->School_model->deleteExtra($_POST['id']);
		
		if ($res)
			echo $okMsg;
		else
			echo $errorMsg;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * Called to create and store the event
	 * @return false if no event is created
	 * @return JSON $data string in JSON format with data to draw the event in the calendar
	 */
	function createEventAction() {
		
		//$this->firephp->log($_POST);
		
		// check if all POST fields are ok
		
		// convert from 'timestamp' to 'datetime'
		$eventStart 		= date('Y-m-d H:i:s',$_POST['eventStart']);
		$eventEnd			= date('Y-m-d H:i:s',$_POST['eventEnd']);
		
		// check if an event exists in the date range
		
		// store the event in the DB and retrieve the 'id' of the event
		$id = $this->School_model->addEvent(
			array (
				'offer_id'		=>$_POST['offerId'],
				'eventStart'	=>$eventStart,
				'eventEnd'		=>$eventEnd,
				'borderColor'	=>'green'
			)
		);
		
		// event created?
		if (!$id) {
			$eventData = null;
			return; 
		}
		
		// prepare data to return
		$eventData['id']			= $id;
		$eventData['title']			= $_POST['offerName'];
		
		// return data event to be drawn in the calendar
		echo json_encode($eventData);
	}
	
	/**
	* Function that returns fullCalendar events from the
	* database table 'schedules'
	* This function is called everytime fullcalendar renders one of the views
	*/
	public function readEventAction() {
		
		// convert from unix timestamp to datetime ... validate later this values
		$start 	= date('Y-m-d H:i:s',$_GET['start']);
		$end	= date('Y-m-d H:i:s',$_GET['end']);

		$this->School_model->flushPastEvents($start, $end);
		$this->School_model->flushOffers();
	
		// get event from db
		$results = $this->School_model->getEvent(array('start'=>$start,'end'=>$end)); 
		$this->firephp->log($results);
		
		if ($results) {
			// fix JSON
			foreach ($results as $key=>$value) {
				$results[$key]['editable']	= $results[$key]['editable'] == 0 ? false:true;
				$results[$key]['allDay']	= $results[$key]['allDay'] == 0 ? false:true;
			}
			echo json_encode($results);
		}
		else {
			echo false;
		}
	}
	
	public function updateEventAction() {
		
	}
	
	public function deleteEventAction() {
		
	}
	
	
	
	
	
	
	public function createReservationAction() {
		
	}
	
	public function readReservationAction() {
		
		echo $this->School_model->readReservation();
	}
	
	public function updateReservationAction() {
		
	}
	
	public function deleteReservationAction() {
		
	}
	
	
	
	
	
	
	
	/**
	* Function to fill the dropbox options with all available offers
	* when an calendar event is drawn
	*/
	public function availableOffers() {
	
		//echo $this->School_model->old_getAvailableOffers();
		$options = array('active'=>'yes','available'=>true,'datatype'=>'json');
		echo $this->School_model->getOffer($options);
	}
	
	
	
	/**
	 * Function that retrieve a json file with
	 * all extras available to be included in the
	 * given offer
	 * $_GET['offerId']
	 * $_GET['userId']
	 */
	public function availableExtras() {
		
		$offerId = $_GET['offerId'];
		
		$users_id = $this->ion_auth->get_user()->id;
		//$userId = $_GET['userId'];
		//$offerId = 6;
		//$userId = 7;
	
		// get all extra's associated to the given offer
		$this->db->select('extra_id');
		$this->db->from('extra_offer');
		$this->db->where('offer_id',$offerId);
		$offerExtra = $this->db->get()->result();
		foreach ($offerExtra as $key => $value) {
			$offerExtra[$key] = $value->extra_id;
		}
	
		$this->db->flush_cache();
	
		$this->db->select('*');
		$this->db->from('extra');
		$this->db->where('included_in_offer',1);
		$this->db->where('users_id',$users_id);
		
		// dont show extras that are already part of this offer 
		if ($offerExtra)
			$this->db->where_not_in('id',$offerExtra);
		
		$result = $this->db->get()->result();
		
		echo json_encode($result);
	}
	
	
	
	
	public function addExtraOffer() {
		
		$okMsg 		= '{"Result":"OK"}';
		$errorMsg 	= '{"Result":"ERROR", "Message":"Nao foi possivel associar o extra à oferta" }';
		
		$offerId = $_GET['offerId'];
		$extraId = $_GET['extraId'];
		
		$this->db->set('extra_id',$extraId);
		$this->db->set('offer_id',$offerId);
		
		$inserted = $this->db->insert('extra_offer');
		
		if ($inserted)
			echo $okMsg;
		else
			echo $errorMsg;
	}
	
	
	
	
	
	/**
	 * static events only for test 
	 */
	function staticEvents() {
		$year = date('Y');
		$month = date('m');
	
		$var1=json_encode(array(
	
		array(
								'id' 	=> 	111,
								'title' => 	"fixed array server 1",
								'start' => 	"$year-$month-26T10:30:00Z",
								'end' 	=> 	"$year-$month-26T11:30:00Z"
		//'url' => "http://yahoo.com/"
		)
	
		// 		array(
		// 							'id' 	=> 222,
		// 							'title' => "Event2",
		// 							'start' => "$year-$month-20",
		// 							'end' 	=> "$year-$month-22"
		// 							//'url' => "http://yahoo.com/"
		// 		)
	
	
	
	
		));
	
		$stringEvent = '
					[
						{
							"id":		111,
							"title":	"curso inicia��o em grupo",
							"start":	"2011-12-28 10:00:00",
							"end":		"2011-12-28 11:00:00",
							"color":	"fdasfdas",
							"editable":	0,
							"allDay":	false
						}
					]';
	
		$stringTmp = '
				{
					"id":				"1",
					"title":			"Curso Inicia\u00e7\u00e3o em grupo",
					"start":			"2012-12-27 13:00:00",
					"end":				"2012-12-27 14:00:00",
					"editable":			"1",
					"color":			"blue",
					"backgroundColor":	"",
					"borderColor":		"",
					"textColor":		""
				},
				{	"id":				"2","title":"Aula Inicia\u00e7\u00e3o em grupo","start":"2012-12-28 14:00:00","end":"2012-12-28 15:00:00","editable":"1","color":"blue","backgroundColor":"","borderColor":"","textColor":""}
			
			
			';
	
	
		$var2 = json_encode(array(
		array(
					'id'=>			1,
					'title' 	=> 	"test",
					'start' 	=> 	"2011-12-25 13:00:00",
					'end' 		=> 	"2011-12-25 18:00:00",
					'color'		=>	"green",
					'editable'	=>	false,
					'allDay'	=> 	false,
		)
		));
	
		$eventArr = array(
			array(
				'id'=>			111, // be carefull with id's
				'title' 	=> 	"test",
				'start' 	=> 	"2012-02-16 12:00:00",
				'end' 		=> 	"2011-02-16 13:00:00",
				'color'		=>	null,
				
				'editable'	=>	'1',
				'allDay'	=> 	'0',
			)
		);
		$eventArr[0]['editable'] = true;
		$eventArr[0]['allDay'] = true;
		$this->firephp->log($eventArr);
		
		$newJson = '
		[
			{
				"id":		"20",
				"title":	"newjson",
				"start":	"2012-02-08 07:30:00",
				"end":		"2012-02-08 11:00:00",
				"editable":	0,
				"allDay":	0,
				"color":	"blue",
				"bgColor":	null,
				"borderColor":null,
				"textColor":null
			}
		]';
		
		//$eventJson = json_encode($eventArr,JSON_NUMERIC_CHECK);
		$eventJson = json_encode($eventArr);
		$this->firephp->log($eventJson);
		//$this->firephp->log($eventArr[0]);
	
		$tmp = $this->json->encode($eventArr);
	
		echo $eventJson;
		//echo $newJson;
		//echo $tmp;
	}
	
	
	

	
	
	public function tmp() {

		$start 	= date('Y-m-d H:i:s',1331769600);
		$end	= date('Y-m-d H:i:s',1331856000);
		$this->firephp->log('start = '.$start);	
		$this->firephp->log('end = '.$end);	
		
		$options = array('start'=>$start,'end'=>$end);
		
		$result =  $this->School_model->getEvent($options);
		$this->firephp->log($result);
		
		
		
		//echo $errorMsg;
		//echo $this->config->item('hotel_ajaxUrl');
		//$this->School_model->flushOffers();
		//$this->ion_auth->change_password($this->ion_auth->get_user()->id, "sc2", "00");
		//$tmp = $this->School_model->getUserInfo($this->ion_auth->get_user()->id);
		//echo $this->ion_auth->get_user()->id;
		//$this->ion_auth->change_password(4, 'sc2', '00');
		//$opt = array('offer_id'=>10,'eventStart'=>'2011-12-25 13:00:00','eventEnd'=>'2011-12-25 18:00:00');
		//$this->School_model->addEvent($opt);
		//$this->School_model->tmp(); 
		
		//$this->firephp->log($this->School_model->getEvent(array('datatype'=>'json')));
		//$this->firephp->log($this->School_model->getOffer_tmp());
		//$opt 	= array('datatype'=>'array','active'=>'yes,'available'=>false);
		//$opt 	= array('datatype'=>'array','available'=>false);
		//$opt2 	= array('datatype'=>'array');
		
		//$this->firephp->log($this->School_model->getOffer($opt2));
		//$this->firephp->log($this->School_model->getAvailableOffers());
	}
	
	
}

